<script setup>
import { Reads, Writes } from '@/Utils/axiosHelper'
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Edit, Delete } from '@element-plus/icons-vue'

const router = useRouter()

// 数据列表
const ramList = ref([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100]
})

// 搜索条件
const searchForm = reactive({
  earSignal: '',
  electronicEarTag: '',
  fatherNumber: null
})

// 父耳号选项
const fatherNumberOptions = [
  { id: 1, name: '父耳号-001' },
  { id: 2, name: '父耳号-002' },
  { id: 3, name: '父耳号-003' },
  { id: 4, name: '父耳号-004' },
  { id: 5, name: '父耳号-005' }
]

// 获取列表数据
const fetchRamList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null) {
        delete params[key]
      }
    })

    const response = await Reads.get('/Management/GetRamFilesPaged', { params })
    
    if (response.data && response.data.code === 400) {
      console.log('API Response Data:', response.data)
      ramList.value = response.data.data?.data || []
      pagination.total = response.data.data?.totalCount || 0
    } else {
      alert('获取列表失败：' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取公羊档案列表失败:', error)
    alert('获取列表失败：' + (error.response?.data?.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchRamList()
}

// 重置搜索
const handleReset = () => {
  searchForm.earSignal = ''
  searchForm.electronicEarTag = ''
  searchForm.fatherNumber = null
  handleSearch()
}

// 分页处理
const handlePageChange = (page) => {
  pagination.currentPage = page
  fetchRamList()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchRamList()
}

// 编辑
const handleEdit = (row) => {
  router.push({
    name: 'ram-edit',
    params: { id: row.ramId }
  })
}

// 删除
const handleDelete = async (row) => {
  console.log(row.ramId)
  if (!confirm(`确定要删除耳号为 "${row.earSignal}" 的公羊档案吗？`)) {
    return
  }

  try {
    const response = await Writes.delete(`/Management/DeleteRamFile`, {
      data: {
        ramId: row.ramId
      }
    })
    
    if (response.data && response.data.code === 200) {
      alert('删除成功！')
      fetchRamList()
    } else {
      alert('删除失败：' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('删除公羊档案失败:', error)
    alert('删除失败：' + (error.response?.data?.message || '网络错误'))
  }
}

// 格式化显示
const formatFatherNumber = (value) => {
  const option = fatherNumberOptions.find(item => item.id === value)
  return option ? option.name : value
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 格式化性别
const formatGender = (value) => {
  const genderMap = { 1: '公', 2: '母' }
  return genderMap[value] || value
}

// 格式化基因等级
const formatGeneRank = (value) => {
  const rankMap = { 1: '后备级', 2: '核心级', 3: '生产级', 4: '未定级' }
  return rankMap[value] || value
}

// 格式化品种
const formatVariety = (value) => {
  const varietyMap = { 
    1: '杜泊', 2: '澳洲白', 3: '萨福克', 4: '杜湖', 
    5: '杜杜湖', 6: '萨杜湖', 7: '澳湖', 8: '湖羊', 9: '澳杜湖' 
  }
  return varietyMap[value] || value
}



// 组件挂载时获取数据
onMounted(() => {
  fetchRamList()
})
</script>

<template>
  <div class="ram-list-container">


    <!-- 搜索区域 -->
    <div class="search-section">
      <form class="search-form">
        <div class="form-row">
          <div class="form-group">
            <label>耳号</label>
            <input
              v-model="searchForm.earSignal"
              type="text"
              class="form-control"
              placeholder="请输入耳号"
              @keyup.enter="handleSearch"
            />
          </div>
          <div class="form-group">
            <label>电子耳标号</label>
            <input
              v-model="searchForm.electronicEarTag"
              type="text"
              class="form-control"
              placeholder="请输入电子耳标号"
              @keyup.enter="handleSearch"
            />
          </div>
          <div class="form-group">
            <label></label>
          </div>
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>父耳号</label>
            <select
              v-model="searchForm.fatherNumber"
              class="form-control"
            >
              <option value="">请选择父耳号</option>
              <option
                v-for="option in fatherNumberOptions"
                :key="option.id"
                :value="option.id"
              >
                {{ option.name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label></label>
          </div>
          <div class="form-group button-group-right">
            <button type="button" class="btn btn-primary" @click="handleSearch" :disabled="loading">
              搜索
            </button>
            <button type="button" class="btn btn-secondary" @click="handleReset">
              重置
            </button>
          </div>
        </div>
      </form>
    </div>



    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="ramList"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column prop="earSignal" label="耳号" width="120" align="center" />
        <el-table-column prop="electronicEarTag" label="电子耳标号" width="140" align="center" />
        <el-table-column prop="fatherNumber" label="父耳号" width="120" align="center">
          <template #default="{ row }">
            {{ formatFatherNumber(row.fatherNumber) }}
          </template>
        </el-table-column>
        <el-table-column prop="variety" label="品种" width="120" align="center">
          <template #default="{ row }">
            {{ formatVariety(row.variety) }}
          </template>
        </el-table-column>
        <el-table-column prop="geneRank" label="基因等级" width="100" align="center">
          <template #default="{ row }">
            {{ formatGeneRank(row.geneRank) }}
          </template>
        </el-table-column>
        <el-table-column prop="dateofBirth" label="出生日期" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.dateofBirth) }}
          </template>
        </el-table-column>
        <el-table-column prop="birthWeight" label="出生重量(kg)" width="120" align="center" />
        <el-table-column prop="placeOfBirth" label="位置" width="120" align="center" />
        <el-table-column prop="note" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
                :icon="Edit"
                circle
                title="编辑"
              />
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
                :icon="Delete"
                circle
                title="删除"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="pagination.pageSizes"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.ram-list-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s ease;
  text-decoration: none;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-icon {
  width: 16px;
  height: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa !important;
  color: #495057 !important;
  font-weight: 600 !important;
  border-bottom: 1px solid #dee2e6 !important;
  padding: 12px 0 !important;
  font-size: 14px !important;
}

:deep(.el-table td) {
  border-bottom: 1px solid #e9ecef;
  padding: 12px 0 !important;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #f8f9fa;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f1f3f4 !important;
}

/* 操作按钮样式 */
.action-buttons-cell {
  display: flex;
  justify-content: center;
  gap: 8px;
}

:deep(.el-button--small) {
  padding: 8px !important;
  font-size: 14px !important;
}

:deep(.el-button--primary) {
  background-color: #007bff !important;
  border-color: #007bff !important;
}

:deep(.el-button--danger) {
  background-color: #dc3545 !important;
  border-color: #dc3545 !important;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  justify-content: center;
  padding: 20px !important;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next),
:deep(.el-pagination .el-pager li) {
  border-radius: 4px !important;
  margin: 0 4px !important;
}

:deep(.el-pagination .el-pager li:hover) {
  background-color: #e9ecef !important;
}

:deep(.el-pagination .el-pager li.active) {
  background-color: #007bff !important;
  color: white !important;
  border-color: #007bff !important;
}

/* 搜索区域样式 - 完全匹配DescendantFromView.vue风格 */
.search-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

.form-group.button-group {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  gap: 10px;
}

.button-group-right {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-items: flex-end;
  height: 38px;
}

.form-control {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  width: 100%;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.form-control::placeholder {
  color: #999;
}

select.form-control {
  cursor: pointer;
  height: 38px;
}

/* 按钮样式优化 */
:deep(.el-button--primary) {
  background-color: #007bff !important;
  border-color: #007bff !important;
}

:deep(.el-button--default) {
  border-radius: 4px !important;
}
</style>